
import { Portal, Image, appLocalStorage, Message } from "magic-ui-react"
import { useEffect, useRef, useState } from "react"
import { CSSTransition } from "react-transition-group"
import styles from './styles.module.less'
import { loginApi, getCurrentUserInfoApi, registerApi } from "@/services"
import { appConfigActions } from "@/store/appConfigSlice"
import { userActions } from "@/store/userSlice"
import { useAppDispatch, useAppSelector } from "@/utils/hooks"
import { isEmpty, omit } from "lodash"
import { offActions } from "@/store/offSlice"

/**
 * 登录弹出框
 * @returns ReactNode
 */
const LoginModal = () => {

  const [isLogin, setIsLogin] = useState(true);
  const [username, setUsername] = useState('');
  const [password, setPassword] = useState('');
  const [passwordConfirm, setPasswordConfirm] = useState('');

  const dispatch = useAppDispatch()
  const nodeRef = useRef(null)
  const {
    off: {
      login
    }
  } = useAppSelector(state => state)

  const submitLogin = async () => {
    try {
      if (isEmpty(username) || isEmpty(password)) {
        return
      }
      const res = await loginApi({
        username,
        password
      })

      appLocalStorage.setValue('token', res.data.token)

      const userInfoRes = await getCurrentUserInfoApi()
      const appConfig = userInfoRes.data?.appConfig
      if (!isEmpty(appConfig)) {
        dispatch(appConfigActions.initAppConfig(JSON.parse(appConfig)))
      }

      const userInfo = omit(userInfoRes.data, 'appConfig')
      dispatch(userActions.updateUserInfo(userInfo))
      appLocalStorage.setValue('userInfo', userInfo)

      dispatch(offActions.update({
        login: false
      }))
      Message.success('登录成功')
    } catch (error: any) {
      Message.success(error.message)
    }
  }

  const submitRegister = async () => {
    try {
      if (isEmpty(username) || isEmpty(password) || isEmpty(passwordConfirm)) {
        Message.warning('信息不完整')
        return
      }
      if (password !== passwordConfirm) {
        Message.warning('请确认密码受否一致')
        return
      }
      await registerApi({
        username,
        password
      })
      Message.success('注册成功')
      submitLogin()
    } catch (error) {
      Message.error('注册失败')
    }
  }

  const init = () => {
    setUsername('')
    setPassword('')
    setPasswordConfirm('')
  }

  useEffect(() => {
    init()
  }, [login, isLogin])

  useEffect(() => {
    setIsLogin(true)
  }, [login])

  return (
    <CSSTransition
      in={login}
      timeout={{
        enter: 300,
        exit: 200
      }}
      nodeRef={nodeRef}
      classNames="modal"
      unmountOnExit
    >
      <Portal visible={true}>
        <div
          className={styles.LoginModal}
          onClick={(e) => {
            dispatch(offActions.update({
              login: false
            }))
            e.stopPropagation()
          }}
        >
          <div
            ref={nodeRef}
            onClick={(e) => {
              e.stopPropagation()
            }}
            className={styles.content}
          >
            <Image width={60} height={60} src='logo/one/android-chrome-192x192.png' />
            <div className="flex flex-col gap-5 w-full">
              <input
                className={styles.loginInput}
                name="new-tab-username"
                placeholder="用户名"
                aria-label="username"
                value={username}
                onChange={(e) => {
                  setUsername(e.target.value)
                }}
                type="text"
              />
              <input
                className={styles.loginInput}
                name="new-tab-password"
                placeholder="密码"
                aria-label="password"
                value={password}
                onChange={(e) => {
                  setPassword(e.target.value)
                }}
                type="password"
              />
              {!isLogin && (
                <input
                  className={styles.loginInput}
                  name="new-tab-passwordConfirm"
                  placeholder="密码"
                  aria-label="passwordConfirm"
                  value={passwordConfirm}
                  onChange={(e) => {
                    setPasswordConfirm(e.target.value)
                  }}
                  type="password"
                />
              )}

            </div>

            <div className="w-full">
              <button
                className={styles.loginBtn}
                onClick={() => {
                  if (isLogin) {
                    submitLogin()
                  } else {
                    submitRegister()
                  }
                }}>
                {isLogin ? '登录' : '确定'}
              </button>
              <div className="flex justify-center mt-4 gap-2">
                <span>
                  {isLogin ? '暂无账号' : '已有账号'}
                </span>
                <span
                  onClick={() => {
                    setIsLogin(!isLogin)
                  }}
                  className="cursor-pointer text-yellow-400 hover:text-yellow-500"
                >
                  {isLogin ? '注册' : '登录'}
                </span>
              </div>
            </div>
          </div>
        </div>
      </Portal>
    </CSSTransition>
  )
}

export default LoginModal